//
//  MoreListController.m
//  XProgress
//
//  Created by Ondrej Rafaj on 20.8.09.
//  Copyright 2009 Home. All rights reserved.
//

#import "MoreListController.h"
#import "ServerLocations.h"
#import "IconCell.h"
#import "WebController.h"
#import "RssController.h"


@implementation MoreListController

@synthesize xmlPath, activityIndicator;
//@synthesize searchBar;
//@synthesize searchString;





- (void) showMessage:(NSString *) message title:(NSString *) title {
	UIAlertView * alertView = [[UIAlertView alloc] initWithTitle: title message: message delegate: nil cancelButtonTitle: @"OK" otherButtonTitles: nil];
	[alertView show];
	[alertView release];	
}







- (void) parseXMLFileAtURL:(NSString *)URL {
	items = [[NSMutableArray alloc] init];
	
	//you must then convert the path to a proper NSURL or it won't work
	NSURL *xmlURL = [NSURL URLWithString:URL];
	
	// here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
	// this may be necessary only for the toolchain
	xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
	
	// Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
	[xmlParser setDelegate:self];
	
	// Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
	[xmlParser setShouldProcessNamespaces:NO];
	[xmlParser setShouldReportNamespacePrefixes:NO];
	[xmlParser setShouldResolveExternalEntities:NO];
	
	[xmlParser parse];
}

- (void) doGetData:(NSString *) search {
	if ([items count] == 0) {
		NSString * path = kXprogressAppMoreMenu;
		unsigned int length = [search length];
		if (length > 0) {
			path = [path stringByAppendingString: @"?search="];
			path = [path stringByAppendingString: search];
		}
		[self parseXMLFileAtURL:path];
		[path release];
	}
}

- (void) searchBarSearchButtonClicked: (UISearchBar *) sb {
	[items removeAllObjects];
	[self doGetData: [sb text]];
	//[searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)sb {
    [sb resignFirstResponder];
}



- (void)parserDidStartDocument:(NSXMLParser *)parser {
	NSLog(@"found file and started parsing");
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
	NSString * errorString = [NSString stringWithFormat:@"Unable to download dictionary database from web site (Error code %i )", [parseError code]];
	NSLog(@"error parsing XML: %@", errorString);
	
	UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[errorAlert show];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
	//NSLog(@"found this element: %@", elementName);
	currentElement = [elementName copy];
	
	if ([elementName isEqualToString:@"item"]) {
		// clear out our story item caches...
		item = [[NSMutableDictionary alloc] init];
		currentTitle = [[NSMutableString alloc] init];
		currentType = [[NSMutableString alloc] init];
		currentImage = [[NSMutableString alloc] init];
		currentVariable = [[NSMutableString alloc] init];
	}
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
	
	//NSLog(@"ended element: %@", elementName);
	if ([elementName isEqualToString:@"item"]) {
		// save values to an item, then store that item into the array...
		[item setObject:currentTitle forKey:@"name"];
		[item setObject:currentType forKey:@"type"];
		[item setObject:currentImage forKey:@"image"];
		[item setObject:currentVariable forKey:@"variable"];
		[items addObject:[item copy]];
		NSLog(@"adding item: %@", currentTitle);
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
	//NSLog(@"found characters: %@", string);
	// save the characters for the current item...
	if ([currentElement isEqualToString:@"name"]) [currentTitle appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
	else if ([currentElement isEqualToString:@"type"]) [currentType appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
	else if ([currentElement isEqualToString:@"image"]) [currentImage appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
	else if ([currentElement isEqualToString:@"variable"]) [currentVariable appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {
	
	[activityIndicator stopAnimating];
	[activityIndicator removeFromSuperview];
	
	NSLog(@"all done!");
	NSLog(@"items array has %d items", [items count]);
	[funcTable reloadData];
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [items count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	static NSString *CellIdentifier = @"MyCell";
	//UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
	IconCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	if (cell == nil){
		//NSLog(@"New Cell Made");
		
		NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"IconCell" owner:nil options:nil];
		
		for(id currentObject in topLevelObjects)
		{
			if([currentObject isKindOfClass:[IconCell class]])
			{
				cell = (IconCell *) currentObject;
				break;
			}
		}
	}
	
	
	int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
	[[cell cellTitle] setText: [[items objectAtIndex: storyIndex] objectForKey: @"name"]];
	//[[cell imageView] setImage:[UIImage imageNamed: [[items objectAtIndex: storyIndex] objectForKey: @"image"]]];
	//NSString *aaaa = [[items objectAtIndex: storyIndex] objectForKey: @"variable"];
	[cell loadRemotePicture: [[items objectAtIndex: storyIndex] objectForKey: @"image"]];
	
	return cell;	
}

//- (void) tableView:(UITableView *) tableView touchesBegan

// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
	NSString *type = [[items objectAtIndex: storyIndex] objectForKey: @"type"];
	if ([type isEqualToString: @"web"]) {
		WebController *controller = [[WebController alloc] initWithNibName:@"WebController" bundle:nil];
		controller.startTitle = [[items objectAtIndex: storyIndex] objectForKey: @"name"];
		controller.startUrl = [[items objectAtIndex: storyIndex] objectForKey: @"variable"];
		[[self navigationController] pushViewController:controller animated:YES];
		[controller release], controller = nil;
	}
	else if ([type isEqualToString: @"rss"]) {
		RssController *controller = [[RssController alloc] init];
		controller.title = [[items objectAtIndex: storyIndex] objectForKey: @"name"];
		controller.startUrl = [[items objectAtIndex: storyIndex] objectForKey: @"variable"];
		[[self navigationController] pushViewController:controller animated:YES];
		[controller release], controller = nil;
	}
	else [self showMessage: @"Unknown data type" title: @"Error!"];
}



/*
 
 - (void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event {
 if (searchBar) {
 [searchBar resignFirstResponder];
 //[self updateLabel];
 //if (moveViewUp) [self scrollTheView:NO];
 }
 [super touchesBegan: touches withEvent: event];
 }
 
 
 
 
 */



- (void)viewDidAppear:(BOOL)animated {
	//[self setNavigationBarHidden: NO];
    [super viewDidAppear:animated];
	//[UIApplication sharedApplication].statusBarHidden = YES;
	[self doGetData: searchString];
	cellSize = CGSizeMake([funcTable bounds].size.width, 60);
}







/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
 [super viewDidLoad];
 }
 */

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [currentElement release];
	[xmlParser release];
	[items release];
	[item release];
	[currentTitle release];
	[currentImage release];
	[currentType release];
	[currentVariable release];
	[super dealloc];
	
}


@end
